package com.jt.www.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.jt.www.common.service.ExpirationRemindService;
import com.jt.www.dao.mapper.messageinfo.MessageInfoEntityMapper;
import com.jt.www.model.mail.dto.MailBean;
import com.jt.www.model.renewal.PolicyExpirationVO;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.vo.renewal.PolicyMsgQo;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.mail.MailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.ArrayList;
import java.util.List;

@Service
@SuppressWarnings("unchecked")
public class ExpirationRemindServiceImpl implements ExpirationRemindService {

    public static final Logger log = LoggerFactory.getLogger(ExpirationRemindServiceImpl.class);

    private static final String POLICY_STATUS = "10";//已出单
    private static final String SOURCE = "00";//00（pc） 01（app）
    private static final String CHANNEL_CODE = "edu";
    @Autowired
    MailUtil mailUtil;
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    private InsClient insClient;
    @Autowired
    private MessageInfoEntityMapper messageInfoEntityMapper;

    @Value("${jtpf.remindemail.email}")
    private String email;

    @Override
    public void renewalEffect(int open) {

        String findCode = "EDU_" + System.currentTimeMillis();

        PolicyMsgQo policyMsgQo = new PolicyMsgQo();

        List<PolicyExpirationVO> holderList = new ArrayList<PolicyExpirationVO>();
        //获取系统1月后的日期
        String oneMonthEndDate = DateUtils.getAfterMonthTime(DateUtils.DATE_FORMAT_YYYY_MM_DD);
        //获取系统一周后的时间
        String polEndWeekLater = DateUtils.getAfterWeakTime(DateUtils.DATE_FORMAT_YYYY_MM_DD);
        //获取系统3天后的时间
        String ThreeDaysLater = DateUtils.getAfterDay(DateUtils.DATE_FORMAT_YYYY_MM_DD);
        //获取系统3天前的时间
        String threeDaysAgo = DateUtils.getTreelastTime(DateUtils.DATE_FORMAT_YYYY_MM_DD);

        //已出单状态
        policyMsgQo.setPolicyStatus(POLICY_STATUS);

        policyMsgQo.setSource(SOURCE);

        policyMsgQo.setChannelCode(CHANNEL_CODE);
        log.debug("开始调用ins,获取续保保单");
        try {
            policyMsgQo.setPolicyEndDate(oneMonthEndDate);
            log.debug(findCode + "投保中心请求开始时间{}", System.currentTimeMillis());
            //查询保单止期距当前日期一月的保单
            log.debug(findCode + "请求投保中心参数 insManagerQo= {}", JSON.toJSONString(policyMsgQo));
            ResponseEntity<GenericListResponse<PolicyExpirationVO>> responseOneMonthEndDate = insClient.selectEduExpiration(JSON.toJSONString(policyMsgQo));
            log.info(findCode + "投保中心请求结果(保单止期距当前日期一月){}", JSON.toJSONString(responseOneMonthEndDate));

            policyMsgQo.setPolicyEndDate(polEndWeekLater);
            //查询保单止期距当前日期一周的保单
            log.debug(findCode + "请求投保中心参数 insManagerQo= {}", JSON.toJSONString(policyMsgQo));
            ResponseEntity<GenericListResponse<PolicyExpirationVO>> responseEntityWeek = insClient.selectEduExpiration(JSON.toJSONString(policyMsgQo));
            log.info(findCode + "投保中心请求结果(保单止期距当前日期一周){}", JSON.toJSONString(responseEntityWeek));

            policyMsgQo.setPolicyEndDate(ThreeDaysLater);
            //查询保单止期距当前日期3天的保单
            log.debug(findCode + "请求投保中心参数 insManagerQo= {}", JSON.toJSONString(policyMsgQo));
            ResponseEntity<GenericListResponse<PolicyExpirationVO>> responseDaysLater = insClient.selectEduExpiration(JSON.toJSONString(policyMsgQo));
            log.info(findCode + "投保中心请求结果(保单止期距当前日期3天){}", JSON.toJSONString(responseEntityWeek));


            policyMsgQo.setPolicyEndDate(threeDaysAgo);
            //查询保单止期距当前日期3天的保单
            log.debug(findCode + "请求投保中心参数 insManagerQo= {}", JSON.toJSONString(policyMsgQo));
            ResponseEntity<GenericListResponse<PolicyExpirationVO>> responseDaysAgo = insClient.selectEduExpiration(JSON.toJSONString(policyMsgQo));
            log.info(findCode + "投保中心请求结果(保单止期过期3天){}", JSON.toJSONString(responseEntityWeek));

            if (!CollectionUtils.isEmpty(responseOneMonthEndDate.getBody().getList())) {
                holderList.addAll(responseOneMonthEndDate.getBody().getList());
            }
            if (!CollectionUtils.isEmpty(responseEntityWeek.getBody().getList())) {
                holderList.addAll(responseEntityWeek.getBody().getList());
            }

            if (!CollectionUtils.isEmpty(responseDaysLater.getBody().getList())) {
                holderList.addAll(responseDaysLater.getBody().getList());
            }

            if (!CollectionUtils.isEmpty(responseDaysAgo.getBody().getList())) {
                holderList.addAll(responseDaysAgo.getBody().getList());
            }

            //遍历list 发送续保提醒邮箱
            MailBean mailBean = new MailBean();
            for (PolicyExpirationVO v : holderList) {
                if (open != 2) {//测试时使用 open = 2
                    email = v.getHolderEmail();
                }
                //获取各个保单号,以及投保产品
                String policyNo = v.getPolicyNo();
                String productName = v.getProductName();
                Context context = new Context();
                context.setVariable("policyNo", policyNo);
                context.setVariable("productName", productName);
                context.setVariable("endDate", DateUtils.conver(v.getPolicyEndDate()));
                context.setVariable("userdate", DateUtils.getCurrentTime());

                mailBean.setSubject("江泰续保提醒");
                String content = templateEngine.process("renewalReminderTemplate", context);
                mailBean.setText(content);
                mailBean.setEmail(email);
                mailUtil.sendMailHtml(mailBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询投保单信息异常");
        }
    }
}
